package com.mz.ozy.activity.login;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;

import com.github.penfeizhou.animation.apng.APNGDrawable;
import com.github.penfeizhou.animation.loader.AssetStreamLoader;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.mz.ozy.R;
import com.mz.ozy.WpkApp;
import com.mz.ozy.activity.MainActivity;
import com.mz.ozy.activity.home.HomeActivity1;
import com.mz.ozy.activity.me.CustomServiceActivity;
import com.mz.ozy.activity.me.FriendListActivity;
import com.mz.ozy.activity.me.PromotionTypeActivity;
import com.mz.ozy.activity.me.SettingActivity;
import com.mz.ozy.activity.me.UpdataActivity;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.utils.AddrDbManager;
import com.mz.ozy.utils.LogUtils;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.widget.LoginButtonSpan;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.NotVipDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.tbruyelle.rxpermissions.RxPermissions;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;
import rx.functions.Action1;


/**
 * 启动页
 */
public class SplashActivity extends BaseActivity implements CancelAdapt {
    private static final int MESSAGE_SUCCESS = 1000;
    //    @BindView(R.id.ivImage)
//    ImageView mIvImage;
    @BindView(R.id.ivCenter)
    ImageView mIvCenter;

    @BindView(R.id.permissionLayout)
    LinearLayout permissionLayout;

//    @BindView(R.id.ivBottom)
//    ImageView mIvBottom;

//    private long duration = 2000;
//    @SuppressLint("HandlerLeak")
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what == MESSAGE_SUCCESS) {
//                startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                finish();
//            }
//        }
//    };
//    private APNGDrawable apngDrawable;
//    private APNGDrawable apngDrawable1;

    private APNGDrawable apngDrawable2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        //初始化
        initData();
//        RxPermissions.getInstance(this)
//                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
//                .subscribe(new Action1<Boolean>() {
//                    @Override
//                    public void call(Boolean aBoolean) {
//                        if (aBoolean) {
//                            initData();
//
//                        } else {
//                            ToastUtils.showToast("为了功能正常使用，请您开启存储权限");
//                        }
//                    }
//                });
    }

    private void initData() {
        //发送延时消息，通知动画结束
//        handler.sendEmptyMessageDelayed(MESSAGE_SUCCESS,
//                duration);
//        AssetStreamLoader assetLoader = new AssetStreamLoader(SplashActivity.this, "spla_logo.png");
//        apngDrawable = new APNGDrawable(assetLoader);
//        mIvImage.setImageDrawable(apngDrawable);
//        apngDrawable.setLoopLimit(1);

//        AssetStreamLoader assetLoader1 = new AssetStreamLoader(SplashActivity.this, "spla_bott.png");
//        apngDrawable1 = new APNGDrawable(assetLoader1);
//        mIvBottom.setImageDrawable(apngDrawable1);
//        apngDrawable1.setLoopLimit(1);
        
        AssetStreamLoader assetLoader2 = new AssetStreamLoader(SplashActivity.this, "spla_center.png");
        apngDrawable2 = new APNGDrawable(assetLoader2);
        mIvCenter.setImageDrawable(apngDrawable2);
        apngDrawable2.setLoopLimit(1);

        apngDrawable2.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
            @Override
            public void onAnimationEnd(Drawable drawable) {
                super.onAnimationEnd(drawable);
                String is_tip = SPUtils.getInstance(SplashActivity.this).getString(Constants.SPName.IS_TIP, "");
                if ("1".equalsIgnoreCase(is_tip)) {
                    check();
                } else {
//                    permissionLayout.setVisibility(View.VISIBLE);
                    TipsDialog();
                }
            }
        });
    }

    @OnClick({R.id.onclickCancel, R.id.onclickOk})
    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.onclickCancel:
//                TipsDialog();
//                break;
//
//            case R.id.onclickOk:
//                TipsDialog();
//                break;
//
//            default:
//
//                break;
//        }
    }

    private void TipsDialog() {
        final BaseDialog dialog = new BaseDialog(SplashActivity.this, R.layout.dialog_login_private, Gravity.CENTER, false);
        final TextView tvContent = dialog.getView(R.id.tv_dialog_content);
        setMsgContent(tvContent);
        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("隐私政策");
        ((TextView) dialog.getView(R.id.btn_cancel)).setText("不同意并退出app");
        ((TextView) dialog.getView(R.id.btn_cancel)).setTextColor(getResources().getColor(R.color.c_333333));
        ((TextView) dialog.getView(R.id.btn_confirm)).setText("同意");
        ((TextView) dialog.getView(R.id.btn_confirm)).setTextColor(getResources().getColor(R.color.white));
        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
                System.exit(0);
            }
        });
        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
                check();
            }
        });
        dialog.toggleDialog();
    }

    private void setMsgContent(TextView tvContent) {
        tvContent.setText("欢迎来到欧卓雅，感谢您对欧卓雅的信任和支持！\n" +
                "为了保障客户端的正常运行以及能够向您提供更全面的功能服务，我们将通过《服务协议》和《隐私政策》帮助您了解我们收集、使用、存储和共享个人信息的情况，以及您所享有的相关权利。\n" +
                "具体内容请您详阅" );
        String content = "《用户协议》";
        SpannableString userSpanStr = new SpannableString(content);
        LoginButtonSpan span = new LoginButtonSpan(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomServiceActivity.go(SplashActivity.this, 0);
            }
        }, R.color.c_047aff);
        userSpanStr.setSpan(span, 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvContent.append(userSpanStr);
        tvContent.append("和");
        String content2 = "《隐私政策》";
        SpannableString userSpanStr2 = new SpannableString(content2);
        LoginButtonSpan span2 = new LoginButtonSpan(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomServiceActivity.go(SplashActivity.this, 1);
            }
        }, R.color.c_047aff);
        userSpanStr2.setSpan(span2, 0, content2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvContent.append(userSpanStr2);
        tvContent.append("全文，我们已采用业内先进的信息保护措施，并会持续优化信息保护技术和安全管理流程，来保护您的个人信息安全。\n");
        tvContent.append("我们将向您申请权限如下和相应说明：\n");
        tvContent.append("1、相机/存储权限：实现头像上传，图片缓存和使用，降低流量消耗。\n");
        tvContent.append("2、位置权限：自动定位配送地址。\n");
        tvContent.append("3、安装应用权限：支持应用内下载和升级。\n");
        tvContent.append("4、获取IMEI和MAC地址：欧卓雅上传到极光推送，而实现定制化推送消息服务。");
        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
    }

    public void check() {
        RxPermissions.getInstance(SplashActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.INTERNET)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        go();
                        if (aBoolean) {
                            SPUtils.getInstance(SplashActivity.this).putString(Constants.SPName.IS_TIP, "1");
                        } else {
                            Log.i("permissions", "权限获取失败");
                        }
                    }
                });
    }

    public void go() {
        WpkApp.ctx.initLaunch();
        String is_login = SPUtils.getInstance(SplashActivity.this).getString(Constants.SPName.IS_LOGIN, "");
        if ("1".equals(is_login)) {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
        } else {
            startActivity(new Intent(SplashActivity.this, PhoneSmsLoginActivity.class));
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (apngDrawable != null) {
//            apngDrawable.stop();
//        }
//        if (apngDrawable1 != null) {
//            apngDrawable1.stop();
//        }
        if (apngDrawable2 != null) {
            apngDrawable2.stop();
        }
    }
}
